#pragma once

#include <iostream>
#include <string>
#include <unordered_map>

class User
{
public:
    User(std::string ip, uint16_t port)
        : _ip(ip), _port(port)
    {
        std::string str = std::to_string(_port);
        _username += _ip;
        _username += "[";
        _username += str;
        _username += "]";
    }

    std::string getname()
    {
        return _username;
    }
    std::string _ip;
    uint16_t _port;

private:
    std::string _username;
};

class Usermanager
{
public:
    Usermanager()
    {
    }
    ~Usermanager()
    {
    }
    void userAdd(User &val)
    {
        _map.insert(std::make_pair(val.getname(), val));
    }
    void userDelet(User &val)
    {
        _map.erase(val.getname());
    }

    std::unordered_map<std::string, User> getmap()
    {
        return _map;
    }

    bool userFind(const std::string &kay)
    {
        return _map.find(kay) != _map.end();
    }

    void allreply(int sockfd, std::string& message)
    {
        for (auto e : _map)
        {
            User user = e.second;
            struct sockaddr_in peer;
            peer.sin_family = AF_INET;
            peer.sin_port = htons(user._port);
            peer.sin_addr.s_addr = inet_addr(user._ip.c_str());
            socklen_t len = sizeof(peer);
            sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&peer, len);
        }
    }
private:
    std::unordered_map<std::string, User> _map;
};